package com.imgpro.controller;


import com.imgpro.Context.BaseContext;
import com.imgpro.Result.Result;
import com.imgpro.Utils.AliyunOSSOperator;
import com.imgpro.service.CommonService;
import com.imgpro.service.UserUrlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;
import java.util.List;

@RestController
@RequestMapping("common")
@Slf4j
@Api(tags = "通用接口，上传等")
public class CommonController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @Autowired
    private UserUrlService userUrlService;


    @Autowired
    private CommonService commonService;


    @ApiOperation("文件存到本地，等待储存")
    @PostMapping("/savefile")
    public Result<String> saveFiles(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.error("上传失败，文件为空");
        }

        // 获取当前项目的根目录
        String projectRootPath = System.getProperty("user.dir");
        File folder = new File(projectRootPath + File.separator + "input");

        // 确保目录存在
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 生成唯一文件名
//        获取原图像拓展名，类似于.jpg和.png等等
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//
        if(!extension.equals(".jpg") && !extension.equals(".png")){
            return Result.error("文件上传失败：" + "请上传JPG或PNG格式的文件");
        }


        String newFileName = BaseContext.getCurrentId()+ extension;

        File dest = new File(folder, newFileName);

        try {
            file.transferTo(dest);
//            TODO 如果有重复怎么办
            Path output =  commonService.doImgPro(folder);

//          将处理好的结果缩小化
            Path output_smallize = commonService.doSmallize(output);

            List<String> urls  = commonService.uploadToOSS(output, output_smallize);




            userUrlService.PreSaveToUserUrl(urls.get(0), urls.get(1));


//           删除原本的结果
            commonService.deleteOrigin(folder);
            commonService.deleteOutPut();

            return Result.success(urls.get(0));

        } catch (Exception e) {
//            e.printStackTrace();
//            如果出现报错也要清空，不然就要出问题了
            commonService.deleteOrigin(folder);
            commonService.deleteOutPut();

            return Result.error("文件上传失败：" + e.getMessage());
        }

    }



    @ApiOperation("文件夹下的文件批量上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){


        try {
            String originName = file.getOriginalFilename();
            log.info("上传一个文件，原本的命名为：{}", originName);

            String url = aliyunOSSOperator.upload(file.getBytes(), originName);

            log.info("这个就是好宝宝的url----{}", url);

            userUrlService.saveToUserUrl(url);

            return Result.success(url);
        } catch (Exception e) {
            log.info("上传失败，出现报错：{}", e.getMessage());
            return Result.error("上传失败" + e.getMessage());
        }
    }

}
